import cherrypy
from Cheetah.Template import Template
from dailyspents import util
from dailyspents.controller.UserController import UserController
from os.path import join

class LoginView(object):
    
    def __init__(self):
        self.userController = None
    
    def makeDefaultNamespace(self):
        nameSpace = {}
        nameSpace['errorMessage'] = None
        nameSpace['message'] = None
        
        return nameSpace
    
    @cherrypy.expose
    def index(self, **kargs):
        
        kargs['errorMessage'] = kargs.get('errorMessage', None)
        kargs['message'] = kargs.get('message', None)
        
        user = cherrypy.session.get('user', None)
        
        if  user is not None:
            raise cherrypy.HTTPRedirect("main")
        else:
            return Template(file = join(util.HTMLPATH, "login.html"), 
                            searchList=[kargs]).respond()
        
    @cherrypy.expose
    def doLogin(self, **kargs):
        self.userController = UserController()
        
        login = kargs.get('login', None)
        password = kargs.get('password', None)
        
        try:
            user = self.userController.getByLogin(login)

            if user.password == password:
                cherrypy.session['user'] = user
                raise cherrypy.HTTPRedirect("/main")
            else:
                raise cherrypy.HTTPRedirect("/index?errorMessage="+\
                                                "Username or password invalid!")
        except Exception, e:
            print e
            raise cherrypy.HTTPRedirect("/index?errorMessage="+\
                                                "Username or password invalid!")
    
    @cherrypy.expose
    def doLogout(self):
        nameSpace = self.makeDefaultNamespace()
        cherrypy.session.clear()
        return Template(file = join(util.HTMLPATH, "login.html"), 
                        searchList=[nameSpace]).respond()
